<template>
	<view class="top-sticky" :style="{position: isFixed ? 'fixed' : 'static'}" style="box-sizing: border-box">
		<view class="banner">
			<!-- 系统状态栏 -->
			<view v-if="isBack" class="system-info"></view>
			<!-- 日期展示 -->
			<view class="date-show" style="box-sizing: border-box">
				<view style="display: flex;align-items: center;" @click="backToUrl" v-if="isBack">
					<uni-icons type="back" size="24" :color="backColor"></uni-icons>
				</view>
				<!-- 非自定义 -->
				<view class="flex-date" v-if="showDate">
					<view class="dec-date" @click="decDate()">
						<uni-icons custom-prefix="iconfont" type="icon-jianhao" size="14" color="#fff"></uni-icons>
					</view>
					<uni-datetime-picker style="width: auto !important; flex-grow: 0 !important;" type="date"
						@change="onDateChanged" v-if="chooseItemIndex == 0">
						<view class="date-display" style="margin-left: auto; margin-right: auto">{{ currentDate }}
						</view>
					</uni-datetime-picker>
					<view class="" style="width: auto !important; flex-grow: 0 !important;" v-else>
						<view class="date-display" style="margin-left: auto; margin-right: auto">{{ currentDate }}
						</view>
					</view>
					<view class="add-date" @click="addDate()">
						<uni-icons custom-prefix="iconfont" type="icon-jia" size="14" color="#fff"></uni-icons>
					</view>
				</view>
				<!-- 自定义 -->
				<view class="flex-date" v-else>
					<uni-datetime-picker v-model="betweenTime" type="daterange" @change="chooseDateSure">
						<view class="flex-date">
							<view class="date-display-custom">
								<view class="date-display-custom-date">{{ betweenTime[0] }}</view>
								<uni-icons type="down" size="16" :color="backColor"
									style="padding-left: 4px"></uni-icons>
							</view>
							<view class="date-display-center">至</view>
							<view class="date-display-custom">
								<view class="date-display-custom-date">{{ betweenTime[1] }}</view>
								<uni-icons type="down" size="16" :color="backColor"
									style="padding-left: 4px"></uni-icons>
							</view>
						</view>
					</uni-datetime-picker>
				</view>
        <view style="width: 48rpx;"></view>
      </view>
			<!-- 日期选择 -->
			<view class="choose-content" v-if="showTabs">
				<view v-for="(item,index) in chooseItem" :key="index" class="choose-item"
					:class="{'choose-item-active':chooseItemIndex == index}" @click="selectDate(index)">
					{{item}}
				</view>
			</view>
			<view>
				<slot name="custom"></slot>
			</view>
		</view>
	</view>
</template>

<script>
	import dayjs from "dayjs";
	export default {
		name: 'customRange',
		props: {
			sendTime: {
				type: [String, Number, Array],
				required: false
			},
			index: {
				type: [String, Number],
				required: false
			},
			isBack: {
				type: Boolean,
				default: true
			},
        isFixed: {
            type: Boolean,
            default: true
        },
        showTabs: {
          type: Boolean,
          default: true
        },
        tabIndex: {
          type: Number,
            default: -1,
            required: false
        }
		},
      watch: {
          tabIndex: {
            handler(value) {
                if (parseInt(value) > -1) {
                    this.chooseItemIndex = parseInt(value);
                    this.selectDate(this.chooseItemIndex);
                }
            },
            immediate: true
        }
      },
		data() {
			return {
				currentDate: '', // 当前显示的日期
				activeButton: 'today', // 当前选中的快速按钮
				backColor: 'var(--black-color)',
				betweenTime: [],
				chooseItem: [
					'昨日', '本月', '上月', '近七日', '自定义'
				],
				chooseItemIndex: -1,
				showDate: true,
				backUrl: ''
			};
		},
		mounted() {
			this.getDateInit()
		},
		methods: {
			currentToday() {
				let today = new Date()
				let utcOffset = 8 * 60 * 60 * 1000
				let todayInBeijing = new Date(today.getTime() + utcOffset)
				let todayNow = todayInBeijing.toISOString().split('T')[0]

				let today1 = new Date(todayNow)
				today1.setDate(today1.getDate() + 1)
				let todayNow1 = today1.toISOString().split('T')[0]
				return [todayNow, todayNow1]
			},

			currentYestoday() {
				// 目前日期 以及 时间
				let today_date = dayjs().format('YYYY-MM-DD')
				let today_time = dayjs().format('HH:mm:ss')
				let betweenTimeStart = ''
				let betweenTimeEnd = ''
				// 判断当前时间是否大于08点，如果大于则减一天  否则减二天
				if (today_time > '08:10:00') {
					betweenTimeStart = dayjs(today_date).subtract(1, 'day').format('YYYY-MM-DD')
					betweenTimeEnd = dayjs(betweenTimeStart).add(1, 'day').format('YYYY-MM-DD')
				} else {
					betweenTimeStart = dayjs(today_date).subtract(2, 'day').format('YYYY-MM-DD')
					betweenTimeEnd = dayjs(betweenTimeStart).add(1, 'day').format('YYYY-MM-DD')
				}
				return [betweenTimeStart, betweenTimeEnd]
			},

			currentToMonth() {
				// 获取目标月的 1 号
				let today_var = new Date();
				let beginMonth = new Date(today_var.getFullYear(), today_var.getMonth(), 1);
				let beYear = beginMonth.getFullYear();
				let beMonth = String(beginMonth.getMonth() + 1).padStart(2, '0'); // 修正：加1
				let beDay = String(beginMonth.getDate()).padStart(2, '0');

				let new_today_var = new Date();
				let endMonth = new Date(new_today_var.getFullYear(), new_today_var.getMonth() + 1, 1);
				let enYear = endMonth.getFullYear();
				let enMonth = String(endMonth.getMonth() + 1).padStart(2, '0'); // 修正：加1
				let enDay = String(endMonth.getDate()).padStart(2, '0');
				return [
					`${beYear}-${beMonth}-${beDay}`,
					`${enYear}-${enMonth}-${enDay}`
				]
			},

			currentPreMonth() {
				// 获取目标月的 1 号
				let today_var = new Date();
				let beginMonth = new Date(today_var.getFullYear(), today_var.getMonth() - 1, 1);
				let beYear = beginMonth.getFullYear();
				let beMonth = String(beginMonth.getMonth() + 1).padStart(2, '0'); // 修正：加1
				let beDay = String(beginMonth.getDate()).padStart(2, '0');

				let new_today_var = new Date();
				let endMonth = new Date(new_today_var.getFullYear(), new_today_var.getMonth(), 1);
				let enYear = endMonth.getFullYear();
				let enMonth = String(endMonth.getMonth() + 1).padStart(2, '0'); // 修正：加1
				let enDay = String(endMonth.getDate()).padStart(2, '0');
				return [
					`${beYear}-${beMonth}-${beDay}`,
					`${enYear}-${enMonth}-${enDay}`
				]
			},

			defaultChooseDate(betweenTime, index) {
				this.betweenTime = betweenTime
				this.selectDate(index)
			},
			getDateInit() {

				this.selectDate(this.chooseItemIndex > -1 ? this.chooseItemIndex : 0);
			},

			// 获取今天的日期
			getToday() {
				this.dayCalculate(0)
			},

			// 获取昨天的日期
			getYesterday() {
				this.dayCalculate(24 * 60 * 60 * 1000)
			},

			// 本月
			getToMonth() {
				this.monthCalculate(0)
			},

			// 上月
			getPreMonth() {
				this.monthCalculate(-1)
			},

			isValidDate(dateString) {
				// 正则表达式匹配日期格式：YYYY-MM-DD
				const regex = /^\d{4}-\d{2}-\d{2}$/;
				if (!regex.test(dateString)) {
					return false;
				}
				return true
			},

			// 日期减
			decDate() {
				// 计算今天的日期
				let dataToday = this.currentToday()
				// 计算昨天的日期
				let dataYestoday = this.currentYestoday()
				// 计算本月的日期
				let dataToMonth = this.currentToMonth()
				// 计算上月的日期
				let dataPreMonth = this.currentPreMonth()

				// 日减操作
				if (this.isValidDate(this.currentDate)) {
					let date = new Date(this.betweenTime[0])
					date.setDate(date.getDate() - 1);
					this.currentDate = date.toISOString().split('T')[0]
					this.betweenTime = [this.currentDate, this.betweenTime[0]]

					if (JSON.stringify(this.betweenTime) != JSON.stringify(dataToday) &&
						JSON.stringify(this.betweenTime) != JSON.stringify(dataYestoday)
					) {
						this.chooseItemIndex = -1
					}
					if (JSON.stringify(this.betweenTime) == JSON.stringify(dataYestoday)) {
						this.chooseItemIndex = 0
					}
					this.outBetweenTime()
					return
				}

				// 月减操作
				const originalMonth = this.betweenTime[0]
				const date = new Date(this.betweenTime[0])
				date.setMonth(date.getMonth() - 1);
				const startMonth = date.toISOString().split('T')[0]
				this.betweenTime = [startMonth, originalMonth]
				this.currentDate = this.dateStringMonth(startMonth)

				if (JSON.stringify(this.betweenTime) != JSON.stringify(dataToMonth) &&
					JSON.stringify(this.betweenTime) != JSON.stringify(dataPreMonth)
				) {
					this.chooseItemIndex = -1
				}
				if (JSON.stringify(this.betweenTime) == JSON.stringify(dataToMonth)) {
					this.chooseItemIndex = 1
				}
				if (JSON.stringify(this.betweenTime) == JSON.stringify(dataPreMonth)) {
					this.chooseItemIndex = 2
				}
				this.outBetweenTime()
			},


			// 日期加	
			addDate() {
				// 计算今天的日期
				let dataToday = this.currentToday()
				// 计算昨天的日期
				let dataYestoday = this.currentYestoday()
				// 计算本月的日期
				let dataToMonth = this.currentToMonth()
				// 计算上月的日期
				let dataPreMonth = this.currentPreMonth()
				if (this.isValidDate(this.currentDate)) {
					const originalDate = this.betweenTime[1]
					const date = new Date(this.betweenTime[1])
					date.setDate(date.getDate() + 1)
					this.currentDate = originalDate
					this.betweenTime = [originalDate, date.toISOString().split('T')[0]]

					if (JSON.stringify(this.betweenTime) != JSON.stringify(dataYestoday)) {
						this.chooseItemIndex = -1
					}
					if (JSON.stringify(this.betweenTime) == JSON.stringify(dataYestoday)) {
						this.chooseItemIndex = 0
					}
					this.outBetweenTime()
					return
				}
				const originalMonth = this.betweenTime[1]
				const date = new Date(this.betweenTime[1])
				date.setMonth(date.getMonth() + 1);
				const endMonth = date.toISOString().split('T')[0]
				this.betweenTime = [originalMonth, endMonth]
				this.currentDate = this.dateStringMonth(originalMonth)
				if (JSON.stringify(this.betweenTime) != JSON.stringify(dataToMonth) &&
					JSON.stringify(this.betweenTime) != JSON.stringify(dataPreMonth)
				) {
					this.chooseItemIndex = -1
				}
				if (JSON.stringify(this.betweenTime) == JSON.stringify(dataToMonth)) {
					this.chooseItemIndex = 1
				}
				if (JSON.stringify(this.betweenTime) == JSON.stringify(dataPreMonth)) {
					this.chooseItemIndex = 2
				}
				this.outBetweenTime()
			},

			/**
			 * @param {Object} dateString
			 * 日期月份处理
			 */
			dateStringMonth(dateString) {
				const year = dateString.split('-')[0];
				const month = dateString.split('-')[1];
				return year + '年' + month + '月'
			},

			/**
			 * @param {Object} day
			 * 月份处理
			 */
			monthCalculate(day) {
				// 获取目标月的 1 号
				let today_var = new Date();
				let beginMonth = new Date(today_var.getFullYear(), today_var.getMonth() + day, 1);
				const beYear = beginMonth.getFullYear();
				const beMonth = String(beginMonth.getMonth() + 1).padStart(2, '0'); // 修正：加1
				const beDay = String(beginMonth.getDate()).padStart(2, '0');

				let new_today_var = new Date();
				let endMonth = new Date(new_today_var.getFullYear(), new_today_var.getMonth() + day + 1, 1);
				const enYear = endMonth.getFullYear();
				const enMonth = String(endMonth.getMonth() + 1).padStart(2, '0'); // 修正：加1
				const enDay = String(endMonth.getDate()).padStart(2, '0');

				this.betweenTime = [
					`${beYear}-${beMonth}-${beDay}`,
					`${enYear}-${enMonth}-${enDay}`
				];
				this.currentDate = `${beYear}-${beMonth}月`
				this.outBetweenTime()
			},

			/**
			 * @param {Object} time
			 * 日处理
			 */
			dayCalculate(time) {
				// 目前日期 以及 时间
				let today_date = dayjs().format('YYYY-MM-DD')
				let today_time = dayjs().format('HH:mm:ss')
				let betweenTimeStart = ''
				let betweenTimeEnd = ''
				// 判断当前时间是否大于08点，如果大于则减一天  否则减二天
				if (today_time > '08:10:00') {
					betweenTimeStart = dayjs(today_date).subtract(1, 'day').format('YYYY-MM-DD')
					betweenTimeEnd = dayjs(betweenTimeStart).add(1, 'day').format('YYYY-MM-DD')
				} else {
					betweenTimeStart = dayjs(today_date).subtract(2, 'day').format('YYYY-MM-DD')
					betweenTimeEnd = dayjs(betweenTimeStart).add(1, 'day').format('YYYY-MM-DD')
				}
				this.betweenTime = [betweenTimeStart, betweenTimeEnd]
				this.currentDate = betweenTimeStart
				this.outBetweenTime()
			},

			/**
			 * 日期透传
			 */
			outBetweenTime() {
				this.$emit('update-between-time', this.betweenTime)
				this.$emit('handConfirm', {
					begin_date: this.betweenTime[0] + ' 12:00:00',
					end_date: this.betweenTime[1] + ' 12:00:00'
				})
				this.$emit('between-choose-index', this.chooseItemIndex)
			},

			/**
			 * @param {Object} type
			 * 快速检索日期
			 */
			selectDate(type) {
				this.showDate = true
				this.chooseItemIndex = type
				switch (String(type)) {
					case '0': // 昨日
						this.getYesterday()
						break
					case '1': // 本月
						this.getToMonth()
						break
					case '2': // 上月
						this.getPreMonth()
						break
					case '3': // 近七日
						this.showDate = false
						this.getSevenDay()
						break
					case '4': // 自定义
						this.showDate = false
						this.outBetweenTime()
						break
				}
			},
			
			getSevenDay(){
				// 目前日期 以及 时间
				let today_date = dayjs().format('YYYY-MM-DD')
				let today_time = dayjs().format('HH:mm:ss')
				let betweenTimeStart = ''
				let betweenTimeEnd = ''
				// 判断当前时间是否大于08点，如果大于则减一天  否则减二天
				if (today_time > '08:10:00') {
					betweenTimeEnd = dayjs(today_date).format('YYYY-MM-DD')
					betweenTimeStart = dayjs(betweenTimeEnd).subtract(7, 'day').format('YYYY-MM-DD')
				} else {
					betweenTimeEnd = dayjs(today_date).subtract(1, 'day').format('YYYY-MM-DD')
					betweenTimeStart = dayjs(betweenTimeEnd).subtract(7, 'day').format('YYYY-MM-DD')
				}
				this.betweenTime = [betweenTimeStart, betweenTimeEnd]
				this.outBetweenTime()
			},

			/**
			 * @param {Object} range
			 * 日期选择判断
			 */
			chooseDateSure(range) {
				const oldBetween = this.betweenTime
				if (range[0] == range[1]) {
					uni.showToast({
						title: '日期不能选择同一天',
						icon: 'none',
						duration: 1500
					})
					this.betweenTime = oldBetween
					return
				}
				this.outBetweenTime()
			},

			onDateChanged(stringDate) {
				let dt = new Date(stringDate);
				this.currentDate = stringDate;
				dt = new Date(dt.setDate(dt.getDate() + 1));
				let month = (dt.getMonth() + 1) < 10 ? '0' + (dt.getMonth() + 1) : dt.getMonth() + 1;
				let day = dt.getDate() < 10 ? '0' + dt.getDate() : dt.getDate();
				let endDate = dt.getFullYear() + '-' + month + '-' + day;
				this.betweenTime = [stringDate, endDate];
				this.chooseDateSure([stringDate, endDate]);
			},

			backToUrl() {
				if (this.backUrl != '') {
					uni.navigateTo({
						url: this.backUrl
					})
				} else {
					uni.navigateBack({
						delta: 1
					})
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	/* 全局自定义应用变量 */
	:root_custom {
		--text-color: #181818;
		--area-color: #ffffff;
		--black-color: #000000
	}

	/* 深色模式下的变量 */
	@media (prefers-color-scheme: dark) {
		:root_custom {
			--text-color: #f5f5f5;
			--area-color: #000000;
			--black-color: #ffffff
		}

		.top-sticky {
			background: #1d1d1d !important;
		}

		.uni-calendar__content {
			background: #1d1d1d !important;
		}
	}

	@media (prefers-color-scheme: light) {
		.top-sticky {
			background: #feffff !important;
		}
	}

	.system-info {
		height: var(--status-bar-height);
	}

	.banner {
		width: 100%;
	}

	.date-show {
		display: flex;
		flex-direction: row;
		height: 88rpx;
		justify-content: space-between;
		width: 100%;
		align-items: center;
		padding: 20rpx 30rpx;
	}

	.dec-date {
		height: 54rpx;
		background-color: #0A84FF;
		width: 60rpx;
		text-align: center;
		align-items: center;
		line-height: 54rpx;
		color: #ffffff;
		border-top-left-radius: 12rpx;
		border-bottom-left-radius: 12rpx;
	}

	.add-date {
		height: 54rpx;
		background-color: #0A84FF;
		width: 60rpx;
		text-align: center;
		align-items: center;
		line-height: 54rpx;
		color: #ffffff;
		border-top-right-radius: 12rpx;
		border-bottom-right-radius: 12rpx;
	}

	.date-display {
		width: 210rpx;
		height: 54rpx;
		line-height: 54rpx;
		background-color: var(--bg-center-color);
		font-size: 30rpx;
		font-weight: 600;
		text-align: center;
		padding-left: 16rpx;
		padding-right: 16rpx;
		color: var(--text-color)
	}

	.date-display-custom {
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
	}

	.date-display-custom-date {
		height: auto;
		font-size: 30rpx;
		font-weight: 600;
		text-align: center;
		color: var(--text-color)
	}

	.date-display-center {
		width: 60rpx;
		height: auto;
		font-size: 30rpx;
		text-align: center;
		color: var(--text-color);
		font-weight: 600;
	}

	.flex-date {
		display: flex;
		flex-direction: row;
		justify-content: center;
		flex-grow: 1;
		align-items: center;
	}

	.choose-content {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		height: 54rpx;
		align-items: center;
		padding: 0 30rpx;
		margin-top: 20rpx;
		margin-bottom: 30rpx;
	}

	.choose-item {
		width: 118rpx;
		height: 54rpx;

		text-align: center;
		line-height: 54rpx;
		border-radius: 16rpx;
		font-size: 28rpx;
		color: var(--text-color);
		background: rgba(118, 128, 128, 0.1);
		cursor: pointer;
	}

	.choose-item-active {
		background-color: #0A84FF;
		font-weight: 600;
		color: #ffffff;
	}

	.top-sticky {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		background-color: var(--bg-color);
		z-index: 100;
	}
</style>